//
//  WYRefreshControl.swift
//  weibo
//
//  Created by 王玉东 on 16/4/19.
//  Copyright © 2016年 wyd. All rights reserved.
//

import UIKit

private let RefreshViewHeight: CGFloat = 60

enum WYRefreshStatue: Int {

    case Normal = 0    // 普通状态
    case Pulling = 1    //准备刷新状态
    case Refreshing = 2 //刷新状态
}
class WYRefreshControl: UIControl {
    
    var statue: WYRefreshStatue = .Normal{
    
        didSet{
            switch statue {
            case .Normal: tipLable.text = "下拉刷新"
                indicatorView.stopAnimating()
            if oldValue == .Refreshing {
            
               
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformIdentity
                    var inset = self.scrollView!.contentInset
                    inset.top = inset.top - RefreshViewHeight
                    self.scrollView?.contentInset = inset
                })
            
            }
            
             
            case .Pulling:
                tipLable.text = "马上刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                tipLable.text = "正在刷新"
                indicatorView.startAnimating()
                arrowicon.hidden = true
                sendActionsForControlEvents(.ValueChanged)
              UIView .animateWithDuration(0.25, animations: { () -> Void in
                var inset = self.scrollView!.contentInset
                inset.top = inset.top + RefreshViewHeight
                self.scrollView?.contentInset = inset
              })
              
            }
           // laststa
        }
    }
    
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -RefreshViewHeight, width: ScreenWidth, height: RefreshViewHeight)
        super.init(frame: rect)
        setUI()
    }
    func endRefreshing() {
        
    //statue = .Normal
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*0.9))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let offsetY = scrollView?.contentOffset.y
        let targetOffsetY = -scrollView!.contentInset.top - RefreshViewHeight
        if scrollView!.dragging {
        
            //if statue == .Pulling && offsetY > -124 {
            if statue == .Pulling && offsetY > targetOffsetY{
            statue = .Normal
            }else if statue == .Normal && offsetY < targetOffsetY{
            
            statue = .Pulling
            }
        }else {
            if statue == .Pulling {
            
         print("正在刷新")
                statue = .Refreshing
                indicatorView.startAnimating()
                arrowicon.hidden = true
            }
        
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let myFather = newSuperview as? UIScrollView {
        
        self.scrollView = myFather
            
        myFather.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
            
        }
    }

    private func setUI() {
    
    backgroundColor = UIColor.yellowColor()
        
        addSubview(arrowicon)
        addSubview(tipLable)
        addSubview(indicatorView)
        
        arrowicon.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        tipLable.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
        
        
    
    }
    
    private var scrollView: UIScrollView?
    private lazy var arrowicon:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLable:UILabel = UILabel(text: "上啦刷新", fontSize: 14, textColor: UIColor.darkGrayColor()
    )
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
